import React, { useState, useEffect } from 'react'
import { 
  Layout, 
  Table, 
  Card, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select, 
  message,
  Popconfirm,
  Tooltip
} from 'antd'
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  EyeOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import { deviceAPI } from '../services/api'

const { Content } = Layout
const { Option } = Select
const { TextArea } = Input

const DeviceList = () => {
  const navigate = useNavigate()
  const [devices, setDevices] = useState([])
  const [loading, setLoading] = useState(false)
  const [modalVisible, setModalVisible] = useState(false)
  const [editingDevice, setEditingDevice] = useState(null)
  const [form] = Form.useForm()

  useEffect(() => {
    fetchDevices()
  }, [])

  const fetchDevices = async () => {
    setLoading(true)
    try {
      const response = await deviceAPI.getDevices({ page_size: 100 })
      if (response.code === 200) {
        setDevices(response.data?.devices || [])
      } else {
        message.error('获取设备列表失败')
      }
    } catch (error) {
      message.error('获取设备列表失败')
    } finally {
      setLoading(false)
    }
  }

  const handleCreate = () => {
    setEditingDevice(null)
    form.resetFields()
    setModalVisible(true)
  }

  const handleEdit = (device) => {
    setEditingDevice(device)
    form.setFieldsValue({
      name: device.name,
      description: device.description,
      device_type: device.device_type
    })
    setModalVisible(true)
  }

  const handleDelete = async (deviceId) => {
    try {
      const response = await deviceAPI.deleteDevice(deviceId)
      if (response.code === 200) {
        message.success('设备删除成功')
        fetchDevices()
      } else {
        message.error(response.message || '设备删除失败')
      }
    } catch (error) {
      message.error('设备删除失败')
    }
  }

  const handleSubmit = async (values) => {
    try {
      let response
      if (editingDevice) {
        response = await deviceAPI.updateDevice(editingDevice.device_id, values)
      } else {
        response = await deviceAPI.createDevice(values)
      }

      if (response.code === 200 || response.code === 201) {
        message.success(editingDevice ? '设备更新成功' : '设备创建成功')
        setModalVisible(false)
        fetchDevices()
      } else {
        message.error(response.message || '操作失败')
      }
    } catch (error) {
      message.error('操作失败')
    }
  }

  const getStatusIcon = (status) => {
    switch (status) {
      case 'online':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />
      case 'offline':
        return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />
      case 'error':
        return <ExclamationCircleOutlined style={{ color: '#faad14' }} />
      default:
        return <CloseCircleOutlined style={{ color: '#d9d9d9' }} />
    }
  }

  const getStatusTag = (status) => {
    const statusConfig = {
      online: { color: 'success', text: '在线' },
      offline: { color: 'error', text: '离线' },
      error: { color: 'warning', text: '错误' }
    }
    
    const config = statusConfig[status] || { color: 'default', text: status }
    return <Tag color={config.color}>{config.text}</Tag>
  }

  const columns = [
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status) => getStatusIcon(status)
    },
    {
      title: '设备名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '设备ID',
      dataIndex: 'device_id',
      key: 'device_id',
      width: 300,
    },
    {
      title: '设备类型',
      dataIndex: 'device_type',
      key: 'device_type',
      render: (type) => (
        <Tag color={type === 'direct' ? 'blue' : 'purple'}>
          {type === 'direct' ? '直连设备' : '网关设备'}
        </Tag>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status_tag',
      render: (status) => getStatusTag(status)
    },
    {
      title: '最后在线',
      dataIndex: 'last_seen',
      key: 'last_seen',
      render: (time) => time ? new Date(time).toLocaleString() : '从未在线'
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (time) => new Date(time).toLocaleString()
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="link"
              icon={<EyeOutlined />}
              onClick={() => navigate(`/devices/${record.device_id}`)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button 
              type="link" 
              icon={<EditOutlined />} 
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm
              title="确定要删除这个设备吗？"
              onConfirm={() => handleDelete(record.device_id)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="link"
                danger
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ]

  return (
    <Layout>
      <Content style={{ padding: '24px' }}>
        <Card
          extra={
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleCreate}
            >
              创建设备
            </Button>
          }
        >
          <Table
            columns={columns}
            dataSource={devices}
            rowKey="id"
            loading={loading}
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
            }}
          />
        </Card>

        {/* 创建设备/编辑设备模态框 */}
        <Modal
          title={editingDevice ? '编辑设备' : '创建设备'}
          open={modalVisible}
          onCancel={() => setModalVisible(false)}
          footer={null}
          width={600}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <Form.Item
              name="name"
              label="设备名称"
              rules={[{ required: true, message: '请输入设备名称' }]}
            >
              <Input placeholder="请输入设备名称" />
            </Form.Item>

            <Form.Item
              name="description"
              label="设备描述"
            >
              <TextArea 
                placeholder="请输入设备描述" 
                rows={4}
              />
            </Form.Item>

            <Form.Item
              name="device_type"
              label="设备类型"
              rules={[{ required: true, message: '请选择设备类型' }]}
            >
              <Select placeholder="请选择设备类型">
                <Option value="direct">直连设备</Option>
                <Option value="gateway">网关设备</Option>
              </Select>
            </Form.Item>

            <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
              <Space>
                <Button onClick={() => setModalVisible(false)}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  {editingDevice ? '更新' : '创建'}
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </Content>
    </Layout>
  )
}

export default DeviceList